<?php

namespace lico\Tool\Session;

class File implements \SessionHandlerInterface
{

    public $config;

    public function close()
    {
        return true;
    }

    /**
     * 删除
     */
    public function destroy($sessionId)
    {
        $file = $this->config['savePath'] . DS . $this->config['prefix'] . $sessionId;
        if (file_exists($file)) {
            @unlink($file);
        }
        return true;
    }

    /**
     * 过期删除
     */
    public function gc($maxlifetime)
    {
        $sessionFiles = glob($this->config['savePath'] . DS . $this->config['prefix'] . '*');
        foreach ($sessionFiles as $file) {
            if (file_exists($file) && filemtime($file) + $maxlifetime < time()) {
                @unlink($file);
            }
        }
        return true;
    }

    public function open($savePath, $sessionName)
    {
        $this->config['savePath'] = $savePath;
        if (!is_dir($this->config['savePath'])) {
            mkdir($this->config['savePath'], 0777, true);
        }

        return true;
    }

    /**
     * 读
     */
    public function read($sessionId)
    {
        $file = $this->config['savePath'] . DS . $this->config['prefix'] . $sessionId;

        $info = '';
        if (is_file($file)) {
            $info = (string) @file_get_contents($file);
        }
        return $info;
    }

    /**
     * 写
     */
    public function write($sessionId, $sessionData)
    {
        $file = $this->config['savePath'] . DS . $this->config['prefix'] . $sessionId;
        return @file_put_contents($file, $sessionData) === false ? false : true;
    }
}
